package com.example.myapplication;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class MyRatelistActivity extends AppCompatActivity {

    private ListView listView;
    private ProgressBar progressBar;
    private Button btnDelete;
    private TextView emptyView;
    private ArrayAdapter<String> adapter;
    private final List<String> rateList = new ArrayList<>();
    private final Handler handler = new Handler(Looper.getMainLooper());

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_ratelist);

        // 初始化视图
        listView = findViewById(R.id.listView);
        progressBar = findViewById(R.id.progressBar);
        btnDelete = findViewById(R.id.btn_delete);
        emptyView = findViewById(R.id.nodata);

        // 设置空视图
        listView.setEmptyView(emptyView);

        // 初始化适配器
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, rateList);
        listView.setAdapter(adapter);

        // 设置长按删除监听
        listView.setOnItemLongClickListener((parent, view, position, id) -> {
            deleteRateItem(position);
            return true;
        });

        // 删除按钮点击事件
        btnDelete.setOnClickListener(v -> {
            int checkedPosition = listView.getCheckedItemPosition();
            if (checkedPosition != ListView.INVALID_POSITION) {
                deleteRateItem(checkedPosition);
            }
        });

        // 启动数据加载线程
        new Thread(dataFetchRunnable).start();
    }

    // 删除指定位置的数据项
    private void deleteRateItem(int position) {
        if (position >= 0 && position < rateList.size()) {
            rateList.remove(position);
            adapter.notifyDataSetChanged();
            Toast.makeText(this, "已删除第" + (position+1) + "项", Toast.LENGTH_SHORT).show();
        }
    }

    private final Runnable dataFetchRunnable = new Runnable() {
        @Override
        public void run() {
            // 显示加载状态
            handler.post(() -> {
                progressBar.setVisibility(View.VISIBLE);
                listView.setVisibility(View.GONE);
                btnDelete.setVisibility(View.GONE);
            });

            List<String> tempList = new ArrayList<>();

            try {
                // 原有数据获取逻辑保持不变
                Document doc = Jsoup.connect("https://www.huilvbiao.com/bank/spdb")
                        .timeout(15000)
                        .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
                        .get();

                Element table = doc.selectFirst("table.table-bordered");
                if (table != null) {
                    Elements rows = table.select("tbody tr");

                    for (Element row : rows) {
                        Element currencyElement = row.selectFirst("th a.coin span");
                        Element rateElement = row.selectFirst("td");

                        if (currencyElement != null && rateElement != null) {
                            String currency = currencyElement.text().trim();
                            String rate = rateElement.text().trim();

                            if (!currency.isEmpty() && !rate.isEmpty()) {
                                tempList.add(currency + " ==> " + rate);
                            }
                        }
                    }
                }

                // 新增延迟代码（在数据获取成功后）
                Thread.sleep(3000); // 延迟3秒

            } catch (Exception e) {
                // 异常时也保持加载状态
                try {
                    Thread.sleep(3000); // 异常时同样延迟3秒
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                handler.post(() -> Toast.makeText(MyRatelistActivity.this,
                        "数据加载失败: " + e.getMessage(), Toast.LENGTH_LONG).show());
            }

            // 更新UI
            handler.post(() -> {
                progressBar.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                btnDelete.setVisibility(View.VISIBLE);

                rateList.clear();
                if (!tempList.isEmpty()) {
                    rateList.addAll(tempList);
                    adapter.notifyDataSetChanged();
                } else {
                    emptyView.setVisibility(View.VISIBLE);
                }
            });
        }
    };
}